/*
 * Controller form Klant crud functionality
 */

define([
	"dojo", 
	"dojox/xml/parser",
],
    
function(
	dojo, 
	xmlParser )
{
	var minLat=100000, minLng=100000, maxLat=-100000, maxLng=-100000;
	
	var Services = 
	{
		parse : function(xml) 
		{
			var coords = new Array();
	 		var docNode = xml.documentElement;
	 		
	 		for(var i = 0; i < docNode.childNodes.length; i++){
	 			var node1 = docNode.childNodes[i];
				if (node1.nodeName == "trk") {
					this._parseTrk(node1, coords);
				}
			}
	 		return coords;
		},

		getWayPoints : function(startIndex, endIndex, coords) 
		{
			var result = new Array();
	 		for(var i = startIndex; i < endIndex; i++) {
	 			if (i >= coords.length - 1) {
	 				break;
	 			} else {
	 				result.push({location:coords[i]});
	 			}
			}
	 		return result;
		},
		
		getCentre : function() 
		{
			//return new google.maps.LatLng((minLat + maxLat)/2.0, (minLng + maxLng)/2.0);
			return new google.maps.LatLng(minLat,minLng);
		},
		
		_parseTrk : function(node1, coords) 
		{
	 		for(var i = 0; i < node1.childNodes.length; i++){
				var node2 = node1.childNodes[i];
				if (node2.nodeName == "trkseg") {
			 		for(var i = 0; i < node2.childNodes.length; i++){
						var node3 = node2.childNodes[i];
						if (node3.nodeName == "trkpt") {
							this._parseTrkPt(node3, coords);
						}
			 		}
				}
	 		}
		},
		
		_parseTrkPt : function(node3, coords) 
		{
			var lat = node3.attributes[0].nodeValue;
			var lng = node3.attributes[1].nodeValue;
			coords.push(new google.maps.LatLng(lat, lng));
			
			if (lat < minLat) {minLat = lat};
			if (lat > maxLat) {maxLat = lat};
			if (lng < minLng) {minLng = lng};
			if (lng > maxLng) {maxLng = lng};
		}
	}

	return Services;

});
